package com.cljh.controller;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.cljh.bean.Calendar;
import com.cljh.bean.User;
import com.cljh.controller.page.Code;
import com.cljh.controller.page.Result;
import com.cljh.mapper.CalendarMapper;
//import com.fasterxml.jackson.databind.json.JsonMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/calendar")
public class CalendarController {
    @Autowired
    CalendarMapper calendarMapper;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
//    private static final String CALENDAR+adminId="CALENDAR+adminId";
    public void flushRedis(String key){
        String s = stringRedisTemplate.opsForValue().get(key);
        if (s!=null&&!"".equals(s)){
            stringRedisTemplate.delete(key);
        }
    }
    @GetMapping("/{adminId}")
    public Result list(@PathVariable Integer adminId){
//        List<Calendar> calendars = calendarMapper.selectAll();

        String userStr = stringRedisTemplate.opsForValue().get(Code.CALENDAR+adminId);
        List<Calendar> calendars =null;
        if (StrUtil.isBlank(userStr)){
            calendars = calendarMapper.selectAll(adminId);
            stringRedisTemplate.opsForValue().set(Code.CALENDAR+adminId,JSONUtil.toJsonStr(calendars));
        }else {
            calendars= JSONUtil.toBean(userStr, new TypeReference<List<Calendar>>() {
            }, true);//redis缓存取出数据
        }


        Integer code=calendars !=null ? Code.GET_OK:Code.GET_ERR;
        String msg=calendars!=null ? "查询到信息":"未查询到信息";
        return new Result(code,calendars,msg);
    }
    @GetMapping("/{date}/{adminId}")
    public Result list1(@PathVariable String date, @PathVariable Integer adminId){

        Calendar calendar = calendarMapper.selectByDate(date,adminId);
        
        Integer code=calendar !=null ? Code.GET_OK:Code.GET_ERR;
        String msg=calendar!=null ? "查询到信息":"未查询到信息";
        return new Result(code,calendar,msg);
    }

    @PostMapping
    public Result save(@RequestBody Calendar calendar) {
        Calendar calendar1 = null;
        if (calendar.getDate() != null && calendar.getAdminId() != null) {
            calendar1 = calendarMapper.selectByDate(calendar.getDate(), calendar.getAdminId());
        }

        int save = 0;
        if (calendar1 != null) {
            save = calendarMapper.upd(calendar);
        } else {
            save = calendarMapper.save(calendar);
        }

        flushRedis(Code.CALENDAR+calendar.getAdminId());
        Integer code = save > 0 ? Code.SAVE_OK : Code.SAVE_ERR;
        String msg = save > 0 ? "添加成功" : "添加失败";
        return new Result(code, save, msg);
    }
}
